require 'rubygems'
require 'nokogiri'
require 'open-uri'
require './downloader'
require 'fileutils'

def do_download out_fn, the_url, force = false
  return false if (out_fn.empty? || the_url.empty?)
  return true if (File.exist?(out_fn) && !force)
  puts out_fn
    
  success = true
  File.open(out_fn, "w") do |file|
    begin
      Downloader.open(the_url) do |data, download_size, url_size|
        file.write data
        puts   "#{out_fn} - #{download_size} / #{url_size}"
      end
    rescue Exception
      puts "#{the_url} error not found"
      success = false
    end
  end
  
  if !success
    # hmm, this remmoval don't work :(
    FileUtils::rm(out_fn)
  end
  
  # return status code
  success
end

def gtc2009 out_dir, force=false
  url = "http://developer.download.nvidia.com/compute/cuda/docs/GTC09Materials.htm"
  title_css_selector = ".xl7511001:nth-child(2),.xl8511001:nth-child(2),.xl7911001:nth-child(2)"  
  mp4_medium_css_selector = ".xl7611001:nth-child(8) a"
  flv_css_selector = ".xl7611001:nth-child(7) a"
  pdf_css_selector = ".xl7611001:nth-child(10) a"
  id_css_selector = ".xl7311001"

  doc = Nokogiri::HTML(open(url))

  doc.css(title_css_selector).each do |title|
    the_tile = title.text.strip.gsub(/\W/,'_')
    the_id = title.parent.at_css(id_css_selector)
    id_str = the_id.nil? ? "" : the_id.text.strip

    mp4_href =  title.parent.at_css(mp4_medium_css_selector)
    flv_href = title.parent.at_css(flv_css_selector)
    pdf_href = title.parent.at_css(pdf_css_selector)

    if pdf_href
      the_pdf_href = pdf_href[:href]
      pdf_out_fn = out_dir + "/" + the_id + "_" + the_tile + ".pdf"
      do_download pdf_out_fn, the_pdf_href, force
    end

    mp4_out_fn = ""
    the_mp4_href = ""
    if mp4_href
      the_mp4_href = mp4_href[:href]
      mp4_out_fn = out_dir + "/" + the_id + "_" + the_tile + ".mp4" 
    end
    
    flv_out_fn = ""
    the_flv_href = ""
    if flv_href
      the_flv_href = flv_href[:href]
      flv_out_fn = out_dir + "/" + the_id + "_" + the_tile + ".flv" 
    end
    
    next if !force && (File.exist?(mp4_out_fn) || File.exist?(flv_out_fn))
    
    # try to download the mp4
    if (do_download(mp4_out_fn, the_mp4_href, force))
      # ok good, we downloaded the mp4, nothing more to do for the movie...
    else
      # ok no good, try flv then...
      do_download(flv_out_fn,the_flv_href,force)
    end

  end    
end

gtc2009 "."